// Copyright (c) 2015, The mangorippers. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// The golang stdlib is used here and is licensed under the 3-clause New BSD.
// "code.google.com/p/go.net/html" is a stdlib candidate and falls under the same BSD license.

// Package mangastream_com handles the parsing of mangastream.com htmls for mangoripper.
package mangastream_com

import (
	"log"
	"net/http"
	"strconv"
	"strings"

	"code.google.com/p/go.net/html"
)

// GrokUrl returns an integer cast of the page number,
// or a -1 for when it's the last page in the last release (=="end").
func GrokUrl(url string) (num int) {
	urlSplit := strings.Split(url, "/")
	tail := urlSplit[len(urlSplit)-1]
	num = -1
	if tail != "end" {
		var err error
		num, err = strconv.Atoi(tail)
		if err != nil {
			log.Fatal(err)
		}
	}
	return num
}

// Step parses through the html and returns the current image's and the next page's urls.
func Step(page string) (nextPage string, img string) {
	res, err := http.Get(page)
	if err != nil {
		log.Fatal(err)
	}
	if res.StatusCode < 200 || res.StatusCode > 299 {
		log.Fatal("Server returned error status code: ", res.StatusCode)
	}
	doc, err := html.Parse(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	res.Body.Close()

	// mostly stolen from https://code.google.com/p/go/source/browse/html/example_test.go?repo=net
	// TODO: maybe this should be a for loop instead?
	var f func(*html.Node)
	f = func(n *html.Node) {
		if n.Type == html.ElementNode && n.Data == "a" {
			for _, a := range n.Attr {
				if a.Key == "href" && n.FirstChild.Data == "img" {
					nextPage = a.Val
					img = n.FirstChild.Attr[1].Val
					break
				}
			}
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			f(c)
		}
	}
	f(doc)

	return nextPage, img
}
